package imoney.shared;

import static imoney.shared.Statics.SEPARATOR;

import java.io.Serializable;

/**
 * Utility class helping with creation and reading of cookies on client side.
 * @author Arnaud Peloquin
 *
 */
public class CookieBuilderShared implements Serializable {

	private static final long serialVersionUID = 22022013L;

	public static String createIndexCookieValue(String googleID, int positionInList, String pseudo) {
		return "" + positionInList + SEPARATOR + googleID +
				SEPARATOR + pseudo;
	}
	
	public static String updatePosition(String cookieValue, int newPosition) {
		int idx = cookieValue.indexOf(Statics.SEPARATOR);
		String oldPosition = cookieValue.substring(0, idx);
		cookieValue.replace(oldPosition, ""+newPosition);
		return cookieValue;
	}
	
	/**
	 * Read the position of the person in the context list stored by this cookie.
	 * Note : this method is public because it's used directly by RCP calls, because
	 * the GWT API only give value getters (can't get a Cookie object directly).
	 * @param rawCookieValue : the value of the cookie to read
	 * @return indexOf, the index corresponding to the person
	 */
	public static int readPosition(String rawCookieValue){
		int indexOf = -1;
		int posIndex = rawCookieValue.indexOf(SEPARATOR);
		String toParse = rawCookieValue.substring(0,posIndex);
		try{
			indexOf = Integer.parseInt(toParse);
		}
		catch(NumberFormatException exc){
			System.out.println("rawCookieValue ("+rawCookieValue+") read failed");
		}
		return indexOf;
	}

	/**
	 * Extract the google userID from the string, which should be a cookie value.
	 * @param rawCookieValue
	 * @return the google id
	 */
	public static String readUserId(String rawCookieValue){
		int idIndex = rawCookieValue.indexOf(SEPARATOR);
		int endIndex = rawCookieValue.indexOf(SEPARATOR, idIndex + 1);
		String googleID = rawCookieValue.substring(idIndex+1, endIndex);
		return googleID;
	}

	/**
	 * Extract the pseudo from the string, which should be a cookie value.
	 * @param rawCookieValue
	 * @return the pseudo
	 */
	public static String readPseudo(String rawValue) {
		// find first separator, to ignore
		int startIdx = rawValue.indexOf(SEPARATOR);
		// second separator, interesting
		startIdx = rawValue.indexOf(SEPARATOR, startIdx + 1) + 1;
		String pseudo = rawValue.substring(startIdx, rawValue.length());
		return pseudo;
	}

}
